package org.basis.netty.chat.rpc.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.ServerSocketChannel;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.basis.netty.chat.protocol.MessageCodecSharable;
import org.basis.netty.chat.protocol.ProcotolFrameDecoder;
import org.basis.netty.chat.protocol.RpcRequestMessageHandler;

/**
 * rpc服务端
 *
 * @author Mr_wenpan@163.com 2021/09/28 16:05
 */
public class RpcServer {

    public static void main(String[] args) throws InterruptedException {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            LoggingHandler loggingHandler = new LoggingHandler(LogLevel.INFO);
            // 自定义协议解码器
            MessageCodecSharable messageCodecSharable = new MessageCodecSharable();
            // rpc消息请求处理器
            RpcRequestMessageHandler rpcRequestMessageHandler = new RpcRequestMessageHandler();

            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(ServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {

                // 在client连接建立时为这些client流水线添加处理器
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加自定义的帧解码器，解决黏包半包问题
                    pipeline.addLast(new ProcotolFrameDecoder());
                    pipeline.addLast(loggingHandler);
                    // 用自定义协议解码消息
                    pipeline.addLast(messageCodecSharable);
                    pipeline.addLast(rpcRequestMessageHandler);
                }
            });

            Channel channel = serverBootstrap.bind(8080).sync().channel();
            // 阻塞等待channel关闭
            channel.closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

}
